import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProFormDigit,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProTable
} from "@ant-design/pro-components";
import {Button, Form, message, Modal, Tooltip} from "antd";
import React, {useRef, useState} from "react";
import {OrderedListOutlined, SettingFilled, TransactionOutlined} from "@ant-design/icons";
import {globalApi, globalLoadTableApi, globalLoadTableApiCode, handleGloblApi} from "@/services/admin-api/globalApi";
import {Access, useAccess} from "umi";

export type WorkerWallet = {
  workerId: number;
  workerBalance: number;
  workerTotalCashMoney: number;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
};

export type WorkerWalletRecord = {
  wwrId: number;
  workerId: number;
  orderId: number;
  wwrType: number;
  wwrDesc: string
  beforeMoney: number;
  changeMoney: number;
  afterMoney: number;
  ocId: number;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
};

export const wwrType = await globalApi('/config/dict', {key: 'wwr_type'})

export default () => {
  const access = useAccess()

  const [modalOpen, handleModalOpen] = useState(false);
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  // const [currentRow, setCurrentRow] = useState<ProductType>();

  const columns: ProColumns<WorkerWallet>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: '工作人员ID', dataIndex: 'workerId', valueType: 'digit'},
    {title: '余额', dataIndex: 'workerBalance', valueType: 'money', hideInSearch: true,},
    {title: '总提现金额', dataIndex: 'workerTotalCashMoney', valueType: 'money', hideInSearch: true,},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Access accessible={access.canAuth('worker:wallet:edit')}>
          <Tooltip key={'edit_' + record.workerId} title={"余额变更"}>
            <Button
              size="small" icon={<TransactionOutlined/>} type="primary"
              onClick={async () => {
                form.setFieldsValue({...record});
                handleModalOpen(true);
              }}
            />
          </Tooltip>
        </Access>,
        <Access accessible={access.canAuth('worker:walletLog:list')}>
          <Tooltip key={'list_' + record.workerId} title={"查看流水"}>
            <Button
              size="small" icon={<OrderedListOutlined/>} type="primary"
              onClick={async () => {
                setWorkerId(record.workerId)
                setIsModalOpen(true);
              }}
            />
          </Tooltip>
        </Access>,
      ],
      valueType: 'option',
    },
  ];

  const [isModalOpen, setIsModalOpen] = useState(false)
  const [workerId, setWorkerId] = useState(0)

  const recordColumns: ProColumns<WorkerWalletRecord>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: 'ID', dataIndex: 'wwrId', valueType: 'digit'},
    {title: '工作人员ID', dataIndex: 'workerId', valueType: 'digit', hideInSearch: true,},
    {title: '订单ID', dataIndex: 'orderId', valueType: 'text', hideInSearch: true,},
    {title: '改变前', dataIndex: 'beforeMoney', valueType: 'money', hideInSearch: true,},
    {title: '变动金额', dataIndex: 'changeMoney', valueType: 'money', hideInSearch: true,},
    {title: '最新余额', dataIndex: 'afterMoney', valueType: 'money', hideInSearch: true,},
    {title: '成本ID', dataIndex: 'ocId', valueType: 'digit', hideInSearch: true,},
    {title: '类型', dataIndex: 'wwrType', valueType: 'select', fieldProps: {options: wwrType.data}},
    {title: '描述', dataIndex: 'wwrDesc', valueType: 'text', hideInSearch: true,},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    // {
    //   title: <SettingFilled/>,
    //   render: (_, record) => [
    //     <Button
    //       key={'edit_' + record.workerId} size="small" icon={<TransactionOutlined/>} type="primary"
    //       onClick={async () => {
    //         form.setFieldsValue({...record});
    //         handleModalOpen(true);
    //       }}
    //     />,
    //     <Button
    //       key={'edit_' + record.workerId} size="small" icon={<OrderedListOutlined/>} type="primary"
    //       onClick={async () => {
    //         setWorkerId(record.workerId)
    //         setIsModalOpen(true);
    //       }}
    //     />,
    //   ],
    //   valueType: 'option',
    // },
  ];

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProTable<WorkerWallet>
      columns={columns} actionRef={actionRef}
      search={{span: 4}}
      request={async (param) => globalLoadTableApiCode('/finance/workerWallteTable', 'worker:wallet:list:search', access, param)}
      rowKey={(record) => record.workerId}
      columnsState={{
        defaultValue: {
          delFlag: {show: false},
          createUserId: {show: false},
          updateUserId: {show: false}
        }
      }}/>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/finance/workerWallteChange', value)

        if (success) {
          actionRef.current?.reload();
          return true
        }
      }}
    >
      <ProFormDigit label="workerId" name="workerId" hidden/>
      <ProFormDigit label="订单ID" name="orderId"/>
      <ProFormDigit label="成本ID" name="ocId"/>
      <ProFormSelect label="类型" rules={[{required: true}]} name="wwrType" options={wwrType.data}/>
      <ProFormMoney label="金额" rules={[{required: true}]} name="changeMoney"/>
      <ProFormText label="描述" rules={[{required: true}]} name="wwrDesc"/>
    </ModalForm>

    <Modal destroyOnClose width={1200} open={isModalOpen} onOk={() => {
      setIsModalOpen(false)
    }} onCancel={() => {
      setIsModalOpen(false)
    }}>
      <ProTable<WorkerWalletRecord>
        search={false} params={{workerId}} columns={recordColumns} request={async (param) => {
        console.log('param = ', param)
        const hide = message.loading('正在加载表格');
        const r = await globalApi('/finance/workerWallteRecordTable', param)
        console.log('r = ', r)
        hide();
        message.success('Loading successfully');
        return {success: r.success, data: r.data.data, total: r.data.total}
      }} rowKey={(record) => record.workerId}
        columnsState={{
          defaultValue: {
            delFlag: {show: false},
            createUserId: {show: false},
            updateUserId: {show: false}
          }
        }}/>
    </Modal>

  </PageContainer>
}
